<template>
  <gzhb-page
    :title="PageTitle"
    :btn-name="PageName"
    :has-btn="hasPageBtn"
    @click="pageBtnClick">
    <gzhb-field
      @click="guochen.dialog = true"
      label="任务名称：">
      <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.name" 
        type="textarea" 
        placeholder="" />
      <template slot="right">
        <span class="ui-icon ui-icon__more"></span>
      </template>
    </gzhb-field>
    <gzhb-field
      label="计划时间：">
      <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.finish" 
        type="textarea" 
        placeholder="" />
    </gzhb-field>
    <gzhb-field
      label="任务类型：">
      <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.typeName" 
        type="textarea" 
        placeholder="" />
    </gzhb-field>
    <gzhb-field
      label="执行人：">
      <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.principalName" 
        type="textarea" 
        placeholder="" />
    </gzhb-field>
    <gzhb-field
      label="分配人：">
      <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.assignerName" 
        type="textarea" 
        placeholder="" />
    </gzhb-field>
    <hr class="ui-hr">

    <!-- 过程进度 -->
    <div class="ui-group">
      <div class="ui-group__title">过程进度</div>
      <div class="ui-group__body">
        <ul class="gzhb-process">
          <li v-for="item in reportList" @click="goProcessDetail(item)" class="gzhb-process__item">
            <div class="gzhb-process__inner">
              <div class="guochen clearfix">
                <div class="left">
                  <p class="time">{{item.rptDate | fRptDate}}</p>
                  <p class="desc">汇报内容：{{item.reportContent}}</p>
                </div>
                <div class="right">
                  <p class="proc-num">进度：{{item.compPct}}%</p>
                  <p v-if="item.subTaskSubmits && item.subTaskSubmits.length > 0" class="fj">
                    <span class="ui-icon ui-icon__fj"></span>
                    <span class="num">{{item.subTaskSubmits.length}}</span>
                  </p>
                </div>
                <span class="ui-icon ui-icon__more"></span>
              </div>
            </div>
            <span class="gzhb-process__line"></span>
            <span class="gzhb-process__point"></span>
          </li>
        </ul>
      </div>
    </div>

    <!-- 审批（page===2）的内容 -->
    <div v-if="page == 2" class="vivande_wapper">
      <hr class="ui-hr">
      <div class="ui-group__title">{{ SubmitDialogTitle }}</div>
      <gzhb-field
        label-width="26%"
        :label="SubmitDialog">
        <van-field 
          slot="input"
          rows="1" 
          autosize 
          readonly 
          v-model="SubmitDialogForm.description" 
          type="textarea" 
          placeholder="" />
      </gzhb-field>
      <gzhb-field
        label-width="26%"
        label="审批意见：">
        <van-field 
          slot="input" 
          v-model="SubmitDialogForm.comment" 
          rows="1" 
          type="textarea" 
          placeholder="请输入" 
          autosize />
      </gzhb-field>
      <gzhb-field
        v-if="SubmitStatusFrom.state === 'delay'"
        label-width="26%"
        label="延期时间：">
        <van-field 
          slot="input" 
          v-model="SubmitDialogForm.time" 
          rows="1"
          type="textarea" 
          placeholder="" 
          autosize 
          readonly
          @click="handleShowSubmitTimepopup" />
      </gzhb-field>
      <gzhb-field
        label-width="15%"
        label="">
        <div slot="input" class="ui-cell">
          <gzhb-radio v-model="SubmitDialogForm.status" label="同意">同意</gzhb-radio>
          <gzhb-radio v-model="SubmitDialogForm.status" label="不同意">不同意</gzhb-radio>
        </div>
      </gzhb-field>
    </div>

    <!-- loading -->
    <gzhb-loading :isShow="isLoading"></gzhb-loading>

    <!-- 汇报按钮（显示终止，转交，延期界面） -->    
    <report-btn :isShowPage="isShowctrlBtn" @dataUpdata="handleDataUpdata"></report-btn>

    <!-- 人员搜索 -->
    <detail-search 
      :masterTask="masterTask"
      :ontheWayObj="ontheWayObj"
      :user="user"
      :isShow="isShowHumanSearchPage">
    </detail-search>

    <!-- 过程详情弹窗 -->
    <gzhb-dialog
      :visible.sync="guochen.dialog"
      title="基本信息">
      <gzhb-field
        labelWidth="32%"
        label="任务状态：">
        <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.statLabel" 
        type="textarea" 
        placeholder="" />
      </gzhb-field>
      <gzhb-field
        labelWidth="32%"
        label="结算类型：">
        <van-field 
        slot="input" 
        rows="1" 
        readonly 
        autosize 
        v-model="form.settleTypeName" 
        type="textarea" 
        placeholder="" />
      </gzhb-field>
      <gzhb-field
        v-if="form.slaveDescription"
        labelWidth="32%"
        label="任务描述：">
        <van-field 
          slot="input" 
          rows="1" 
          type="textarea" 
          readonly 
          autosize 
          v-model="form.slaveDescription" 
          placeholder='' />
      </gzhb-field>
      <gzhb-field
        v-if="form.describe"
        labelWidth="32%"
        label="交付物要求：">
        <van-field 
          slot="input" 
          rows="1" 
          type="textarea" 
          readonly 
          autosize 
          v-model="form.describe" 
          placeholder='' />
      </gzhb-field>
    </gzhb-dialog>

    <!-- 时间选择 -->
    <van-popup
      v-model="SubmitDialogForm.show"
      position="bottom">
      <van-datetime-picker
        type="date"
        v-model="SubmitDialogForm.popupTime"
        @cancel="SubmitDialogForm.show = false"
        @confirm="pickTimeConfirm"/>
    </van-popup>
  </gzhb-page>
</template>

<script>
  import axios from '@/axios'
  import qs from 'query-string'
  import moment from 'moment'
  import ReportBtn from "./components/reportBtn.vue"
  import DetailSearch from "./components/detailSearch.vue"
  import { mapGetters } from 'vuex'
  export default {
    components: {
      'report-btn' : ReportBtn,
      'detail-search' : DetailSearch
    },
    data() {
      return {
        // 来源的页面标签
        page: '',

        // 是否显示提交弹框
        isShowSubmitDialog: false,
        ontheWayObj: {},
        SubmitStatusFrom: {
          state: '',
          compPct: ''
        },
        SubmitDialogForm: {
          tip: '',
          id: '',
          taskId: '',
          description: '',
          reportContent: '',
          status: '同意',
          popupTime: '',
          time: '',
          comment: '',
          show: false,
          obj: {}
        },

        // 遮罩
        isLoading: true,

        shifouxxjd: false,
        guochen: {
          dialog: false
        },
        reportList: [],
        form: {
          name: '',
          finish: '',
          typeName: '',
          principalName: '',
          assignerName: '',
          statLabel: '',
          settleTypeName: '',
          slaveDescription: '',
          describe: ''
        },

        //是否显示终止，转交，延期按钮(只在汇报页面显示)
        isShowctrlBtn: true,

        // 人员搜索
        isShowHumanSearch: false,
        masterTask:{},
        ontheWayObj:{},
        user:{},
      }
    },
    computed: {
      ...mapGetters(['isShowHumanSearchPage', 'isShow']),
      SubmitDialogTitle(){
        let title = '申请完成'
        if(this.SubmitStatusFrom.state === 'delay'){
          title = '延期申请'
        } else if(this.SubmitStatusFrom.state === 'relay'){
          title = '转交申请'          
        } else if(this.SubmitStatusFrom.state === 'terminate'){
          title = '终止申请'          
        }

        return title
      },
      
      SubmitDialog(){
        let title = '完成说明'
        if(this.SubmitStatusFrom.state === 'delay'){
          title = '延期原因'
        } else if (this.SubmitStatusFrom.state === 'relay'){
          title = '转交说明'
        } else if (this.SubmitStatusFrom.state === 'terminate'){
          title = '终止原因'
        }

        return title + '：'
      },

      // 顶部标题
      PageTitle(){
        return "任务详情"
      },

      // 底部按钮名称
      PageName(){
        let name = '汇报'
        if(this.page == 2){
          name = '审批'
        }

        return name
      },

      //底部按钮的显示控制
      hasPageBtn(){
        let status = true
        // 当前page不是1，和2的时候，不显示按钮
        // state状态为空的时候，，不显示提交按钮
        if(
          (this.page != 1 && this.page != 2) ||
          (this.page == 1 && this.SubmitStatusFrom.compPct === 100) ||
          (this.page == 1 && this.masterTask.statLabel === '已终止') ||
          (this.page == 1 && Object.keys(this.ontheWayObj).length > 0) ||
          (this.page == 1 && (this.masterTask.principalNo !== this.user.no)) ||
          (this.page == 2 && !Number(this.SubmitStatusFrom.state.length)) ||
          (this.page == 2 && Object.keys(this.ontheWayObj).length === 0 )
        ){
          status = false
        }
        return status
      }
    },
    filters: {
      fRptDate(v) {
        return v.split(' ')[0]
      }
    },
    watch: {
      SubmitStatusFrom:{
        handler(val, oldval){
          let str = ''
          if(this.SubmitStatusFrom.state === 'finish'){
            // 完成状态
            str = `${this.SubmitStatusFrom.obj.rptUserName}在${this.SubmitStatusFrom.obj.rptDate.substr(0, 10)}申请${this.SubmitStatusFrom.name}任务完成。`
          } else if(this.SubmitStatusFrom.state === 'delay'){
            // 延期状态
            str = `${this.SubmitStatusFrom.obj.applyUserName}申请${this.SubmitStatusFrom.name}任务延期到${this.SubmitStatusFrom.obj.newFinishDate.substr(0, 10)}`
          } else if(this.SubmitStatusFrom.state === 'relay'){
            // 转交状态
            // str = `${this.SubmitStatusFrom.obj.applyUserName}申请任务${this.SubmitStatusFrom.name}转交给${this.SubmitStatusFrom.obj.recipientName}`
            str = `${this.SubmitStatusFrom.obj.applyUserName}转交此任务给您，请审批`
          } else if(this.SubmitStatusFrom.state === 'terminate'){
            // 终止状态
            str = `${this.SubmitStatusFrom.obj.rptUserName}申请任务${this.SubmitStatusFrom.name}终止`
          }

          this.SubmitDialogForm.tip = str
        },
        deep:true
      }
    },
    created() {      
      this.getDetailPageData()

      if(this.isShowHumanSearchPage){
        this.$store.commit('SET_HUMAN_SEARCH_PAGE', false)
      }

      // 如果页面不是page===1 ，则不显示控制按钮
      if(Number(this.$route.query.page) !== 1) {
        this.isShowctrlBtn = false
      }
    },
    methods: {
      // 获取主页数据
      getDetailPageData(){
        this.isLoading = true
        let { testOAuthUser, id, token} = this.$route.query
        this.page = this.$route.query.page

        // 设置用户权限(有token字段就储存，否则不进行操作)
        if(token) localStorage.setItem('token', token)
        
        localStorage.setItem('userID', testOAuthUser)
        localStorage.setItem('id', id)
        localStorage.setItem('page', this.page)

        axios.get('getDetailPageData', {
          params: {
            testOAuthUser, 
            id
          }
        }).then(res => {
          this.isLoading = false
          
          this.ontheWayObj = res.ontheWayObj
          this.masterTask = res.masterTask
          this.reportList = res.reportList
          this.user = res.user

          for (let p in this.form) {
            this.form[p] = this.masterTask[p]
          }

          if (this.masterTask.start && this.masterTask.finish) {
            this.form.finish = this.masterTask.start.split(' ')[0] + ' - ' + this.masterTask.finish.split(' ')[0]
          }

          if (this.masterTask.shifouxxjdhb && this.masterTask.shifouxxjdhb == 1) {
            this.shifouxxjd = true
          }

          // 隐藏空或者-1终止的进度汇报
          this.reportList = this.reportList.filter(item=>{
            return item.compPct === 0 || item.compPct > 0
          })

          this.$store.commit('SET_IS_SHOW', !this.isShow)

          this.SubmitStatusFrom = Object.assign(this.SubmitStatusFrom, this.SubmitStatusFrom, this.ontheWayObj)
          this.SubmitStatusFrom.compPct = this.masterTask.compPct
          this.SubmitStatusFrom.name = this.masterTask.name

          if('obj' in this.SubmitStatusFrom){
            this.SubmitDialogForm.time = this.SubmitStatusFrom.obj.newFinishDate && this.SubmitStatusFrom.obj.newFinishDate.substr(0, 10)
            this.SubmitDialogForm.id = this.SubmitStatusFrom.obj.id

            // 状态如果是finish（完成）或者是terminate（终止）时，
            // 任务id与描述是taskId和reportContent， 否则是task，description
            if (this.ontheWayObj.state === 'finish' || this.ontheWayObj.state === 'terminate') {
              this.SubmitDialogForm.taskId = this.SubmitStatusFrom.obj.taskId
              this.SubmitDialogForm.description = this.SubmitStatusFrom.obj.reportContent
            } else {
              this.SubmitDialogForm.taskId = this.SubmitStatusFrom.obj.task
              this.SubmitDialogForm.description = this.SubmitStatusFrom.obj.description          
            }
          }
          
          localStorage.setItem('ontheWayObj', JSON.stringify(this.ontheWayObj))
          localStorage.setItem('reportList', JSON.stringify(this.reportList))
          localStorage.setItem('masterTask', JSON.stringify(this.masterTask))
          localStorage.setItem('user', JSON.stringify(this.user))
        })
      },

      // 点击下方按钮
      pageBtnClick() {
        if (this.page == 1) {
          this.$router.push('/process/add')
        } else if(this.page == 2) {
          this.handleVivandeSubmit()
        }
      },

      // 跳转到详情页面
      goProcessDetail(item) {
        localStorage.setItem('SubmitStatusFrom', JSON.stringify(this.SubmitStatusFrom))
        localStorage.setItem('SubmitDialogForm', JSON.stringify(this.SubmitDialogForm))
        localStorage.setItem('fujian', JSON.stringify(item))
        this.$router.push({ 
          path:'/process/detail', 
          query:{ 
            page: this.$route.query.page
          }
        })
      },

      // 处理审批提交弹框的提交按钮事件
      handleVivandeSubmit(){
        let submitUrl = ''
        if( this.SubmitStatusFrom.state === 'finish' && this.SubmitDialogForm.status === '同意' ){
          // 申请完成同意
          submitUrl = 'taskProgressReportFinish'
        } else if( this.SubmitStatusFrom.state === 'finish' && this.SubmitDialogForm.status === '不同意' ){
          // 申请完成不同意
          submitUrl = 'taskProgressReportDisagree'
        } else if( this.SubmitStatusFrom.state === 'delay' && this.SubmitDialogForm.status === '同意' ){
          // 延期申请同意
          submitUrl = 'taskApplyDelayFinish'
        } else if(this.SubmitStatusFrom.state === 'delay' && this.SubmitDialogForm.status === '不同意'){
          // 延期申请不同意
          submitUrl = 'taskApplyDelayDisagree'
        } else if(this.SubmitStatusFrom.state === 'relay' && this.SubmitDialogForm.status === '同意'){
          // 转交申请同意
          submitUrl = 'taskApplyRelayAgree'
        } else if(this.SubmitStatusFrom.state === 'relay' && this.SubmitDialogForm.status === '不同意'){
          // 转交申请不同意
          submitUrl = 'taskApplyRelayDisagree'
        } else if(this.SubmitStatusFrom.state === 'terminate' && this.SubmitDialogForm.status === '同意'){
          // 终止申请同意
          submitUrl = 'terminateAgree'
        } else if(this.SubmitStatusFrom.state === 'terminate' && this.SubmitDialogForm.status === '不同意'){
          // 终止申请不同意
          submitUrl = 'terminateDisagree'
        }

        axios.post( submitUrl, {
          id: this.SubmitDialogForm.id,
          task: this.SubmitDialogForm.taskId,
          rejectDesc: this.SubmitDialogForm.comment, 
          newFinishDate: this.SubmitDialogForm.time
        }).then(res => {                      
          this.getDetailPageData()
          if(res.succ){
            this.$toast.success(res.msg || '审批成功')
            this.isShowSubmitDialog = false
          } else {
            this.$toast.fail(res.msg || '审批失败')
          }
        })
      },

      // 显示时间弹窗
      handleShowSubmitTimepopup(){
        this.SubmitDialogForm.show = true
      },

      // 选择弹框的时间
      pickTimeConfirm() {        
        this.SubmitDialogForm.time = moment(this.SubmitDialogForm.popupTime).format('YYYY-MM-DD')
        this.SubmitDialogForm.show = false
      },

      // 汇报按钮的功能更新了就触发页面更新
      handleDataUpdata(){
        this.getDetailPageData()
      }
    }
  }
</script>

<style lang="less" scoped>
.gzhb-process__item {
  position: relative;
  padding: 15px 0;
  border-bottom: 1px solid #f1f1f1;
}
.gzhb-process__item:first-child {
  .gzhb-process__line {
    top: 15px;
    height: calc(100% - 15px);
  }
}
.gzhb-process__item:last-child {
  .gzhb-process__line {
    height: 15px;
  }
}
.gzhb-process__item:first-child:last-child {
  .gzhb-process__line {
    height: 0px;
  }
}
.gzhb-process__line {
  position: absolute;
  left: 12px;
  top: 0;
  width: 1px;
  height: 100%;
  background-color: #f1f1f1;
}
.gzhb-process__point {
  position: absolute;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #80c269;
  top: 16px;
  left: 8px;
}
.gzhb-process__inner {
  padding-left: 28px;
}

.guochen {
  padding-right: 46px;
  position: relative;
  .left {
    float: left;
    width: 67.85%;
    padding-right: 10px;
  }
  .right {
    float: right;
    width: 32.15%;
  }
  .time, .proc-num {
    font-size: 3.125vw;
    color: #9a9a9a;
    padding-bottom: 10px;
  }
  .proc-num {
    text-align: right;
  }
  .desc {
    font-size: 3.75vw;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .fj {
    .ui-icon {
      color: #6F7F99;
    }
    text-align: right;
    .num {
      font-size: 3.75vw;
    }
  }
  .ui-icon__more {
    position: absolute;
    right: 2.5vw;
    top: 15px;
  }
}
</style>